package com.github.cyf.cacheManager;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.OrderComparator;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author chenyifan
 * @create 2025-02-06 9:59
 */
@Component
@Slf4j
public class CacheManagerRegistry implements ApplicationRunner, ApplicationContextAware {

    private static final ConcurrentHashMap<String, CacheManager> MANAGER_MAP = new ConcurrentHashMap<>();

    private final CacheManagerTrigger cacheManagerTrigger;
    private ApplicationContext applicationContext;

    public CacheManagerRegistry(CacheManagerTrigger cacheManagerTrigger) {
        this.cacheManagerTrigger = cacheManagerTrigger;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 执行缓存初始化
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            Map<String, CacheManager> beans = applicationContext.getBeansOfType(CacheManager.class);
            List<CacheManager> managers = new ArrayList<>(beans.values());
            managers.sort(new OrderComparator());

            // 打印系统启动日志
            log.info("cache component extensions: ");
            for (CacheManager cacheManager : managers) {
                String beanName = cacheManager.getClass().getSimpleName();
                log.info("{} ==> {}", cacheManager.getCacheName().getName(), beanName);
            }

            // 初始化缓存
            for (CacheManager manager : managers) {
                manager.initCache();
            }

            // 添加定时刷新缓存的任务
            for (CacheManager manager : managers) {
                cacheManagerTrigger.addTask(manager);
            }
        } catch (Exception e) {
            log.error("cache init fail:", e);
            throw new RuntimeException("缓存初始化失败", e);
        }
    }

    /**
     * 注册缓存管理器
     * @param cacheManager
     */
    public static void register(CacheManager cacheManager) {
        MANAGER_MAP.put(cacheManager.getCacheName().getName(), cacheManager);
    }

    /**
     * 刷新特定的缓存
     * @param cacheName 缓存名称
     */
    public static void refreshCache(String cacheName) {
        CacheManager cacheManager = MANAGER_MAP.get(cacheName);
        if (cacheManager == null) {
            log.warn("cache manager is not exist, cacheName: {}", cacheName);
            return;
        }
        cacheManager.refreshCache();
    }

    /**
     * 获取缓存列表
     */
    public static List<String> getCacheNameList() {
        return new ArrayList<>(MANAGER_MAP.keySet());
    }
}